package com.example.thread.CompletableFutures;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
public class CompletableFuturesTest1 {
    /**
     * A supplier that sleeps for a second, and then returns one
     **/
    public static class MySupplier implements Supplier<Integer> {

        @Override
        public Integer get() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //Do nothing
            }
            return 1;
        }
    }

    /**
     * A (pure) function that adds one to a given Integer
     **/
    public static class PlusOne implements Function<Integer, Integer> {

        @Override
        public Integer apply(Integer x) {

            int j = 0;
//            int v = 100 / j;
            return x + 1;
        }
    }

    public static void main(String[] args) throws Exception {
        ExecutorService exec = Executors.newSingleThreadExecutor();
//        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new MySupplier(), exec);
//        System.out.println(f.isDone()); // False
//        CompletableFuture<Integer> f2 = f.thenApply(new PlusOne())
//                .whenComplete((result, ex)->{
//                    if (ex != null) {
//                        log.info("出现了异常");
//                        log.info(ex.getMessage());
//                    } else {
//                        log.info("正常结束 ret={}", result);
//                    }
//
//                })
//                ;
//        log.info("xxxx");
        CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //Do nothing
            }
            log.info("11111");
            int j = 0;
            int v = 100 / j;
            log.info("11112");
        }, exec).whenComplete((ret, thr)->{
            if (ret != null) {
                log.info("2222 ret={}", ret);
            }
            if (thr != null) {
                log.info("thr={}", thr);
            }
        });
        log.info("main end");
//        f2.completeExceptionally()
//        System.out.println(f2.get()); // Waits until the "calculation" is done, then prints 2
    }
}
